import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Box,
  Container,
  Grid,
  Typography,
  Card,
  CardContent,
  CardActions,
  Button,
  Chip,
  LinearProgress,
  Divider,
  Tabs,
  Tab,
  Paper
} from '@mui/material';
import { RootState } from '../redux/store';
import { AppDispatch } from '../redux/store';
import { getPatterns } from '../redux/slices/patternSlice';
import { selectPattern } from '../redux/slices/progressSlice';
import { addAlert } from '../redux/slices/uiSlice';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

const TabPanel = (props: TabPanelProps) => {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`patterns-tabpanel-${index}`}
      aria-labelledby={`patterns-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  );
};

const a11yProps = (index: number) => {
  return {
    id: `patterns-tab-${index}`,
    'aria-controls': `patterns-tabpanel-${index}`,
  };
};

const Patterns: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { patterns, loading } = useSelector((state: RootState) => state.patterns);
  const { overallProgress } = useSelector((state: RootState) => state.progress);
  const [tabValue, setTabValue] = React.useState(0);

  useEffect(() => {
    dispatch(getPatterns());
  }, [dispatch]);

  const handleTabChange = (_: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  const handlePatternSelect = (patternId: string) => {
    dispatch(selectPattern(patternId))
      .unwrap()
      .then(() => {
        navigate(`/patterns/${patternId}`);
      })
      .catch((error: string) => {
        dispatch(addAlert({
          type: 'error',
          message: error
        }));
      });
  };

  if (loading || !patterns.length) {
    return (
      <Box sx={{ width: '100%', mt: 4 }}>
        <LinearProgress />
      </Box>
    );
  }

  const creationalPatterns = patterns.filter(pattern => pattern.category === 'Creational');
  const structuralPatterns = patterns.filter(pattern => pattern.category === 'Structural');
  const behavioralPatterns = patterns.filter(pattern => pattern.category === 'Behavioral');

  const isPatternLocked = (patternId: string) => {
    // 移除模式锁定，允许选择任何模式
    return false;
  };

  const renderPatternCard = (pattern: any) => {
    const locked = isPatternLocked(pattern._id);
    const isCurrentPattern = overallProgress?.currentPattern?._id === pattern._id;
    
    return (
      <Grid item xs={12} sm={6} md={4} key={pattern._id}>
        <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column', opacity: locked ? 0.7 : 1 }}>
          <CardContent sx={{ flexGrow: 1 }}>
            <Typography variant="h6" component="h2" gutterBottom>
              {t(`patterns.names.${pattern.name}`, { defaultValue: pattern.name })}
            </Typography>
            <Chip
              label={t(`patterns.categories_en.${pattern.category}`, { defaultValue: pattern.category })}
              size="small"
              color={
                pattern.category === 'Creational'
                  ? 'primary'
                  : pattern.category === 'Structural'
                  ? 'secondary'
                  : 'info'
              }
              sx={{ mb: 2 }}
            />
            <Typography variant="body2" color="text.secondary">
              {t(`patterns.descriptions.${pattern.name}`, { defaultValue: pattern.description.substring(0, 120) })}...
            </Typography>
          </CardContent>
          <CardActions>
            <Button 
              size="small" 
              onClick={() => handlePatternSelect(pattern._id)}
              disabled={locked && !isCurrentPattern}
            >
              {isCurrentPattern ? t('dashboard.patternCard.continue') : t('dashboard.patternCard.startLearning')}
            </Button>
          </CardActions>
        </Card>
      </Grid>
    );
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        {t('nav.patterns')}
      </Typography>
      
      <Paper sx={{ width: '100%', mt: 3 }}>
        <Tabs
          value={tabValue}
          onChange={handleTabChange}
          indicatorColor="primary"
          textColor="primary"
          centered
        >
          <Tab label={t('patterns.categories.creational.title')} {...a11yProps(0)} />
          <Tab label={t('patterns.categories.structural.title')} {...a11yProps(1)} />
          <Tab label={t('patterns.categories.behavioral.title')} {...a11yProps(2)} />
        </Tabs>
        
        <TabPanel value={tabValue} index={0}>
          <Typography variant="body1" paragraph>
            {t('patterns.categories.creational.description')}
          </Typography>
          <Grid container spacing={3}>
            {creationalPatterns.map(renderPatternCard)}
          </Grid>
        </TabPanel>
        
        <TabPanel value={tabValue} index={1}>
          <Typography variant="body1" paragraph>
            {t('patterns.categories.structural.description')}
          </Typography>
          <Grid container spacing={3}>
            {structuralPatterns.map(renderPatternCard)}
          </Grid>
        </TabPanel>
        
        <TabPanel value={tabValue} index={2}>
          <Typography variant="body1" paragraph>
            {t('patterns.categories.behavioral.description')}
          </Typography>
          <Grid container spacing={3}>
            {behavioralPatterns.map(renderPatternCard)}
          </Grid>
        </TabPanel>
      </Paper>
    </Container>
  );
};

export default Patterns; 